import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:magic_car/common/global.dart';
import 'package:magic_car/util/HttpHelper.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:toast/toast.dart';
import 'package:magic_car/main.dart';

class LoginPage extends StatefulWidget {
  //LoginPage({Key key, this.title,this.role}) : super(key: key);

  //final String title;
  final String role;

  LoginPage(this.role);

  @override
  _MyHomePageState createState() => new _MyHomePageState(this.role);
}

class _MyHomePageState extends State<LoginPage> {
  bool _phoneState, _pwdState = false;
  String _checkStr;
  String roles;
  _MyHomePageState(this.roles);

  TextEditingController _phonecontroller = new TextEditingController();
  TextEditingController _pwdcontroller = new TextEditingController();

  void _checkPhone() {
    if (_phonecontroller.text.isNotEmpty &&
        _phonecontroller.text.trim().length == 11) {
      _phoneState = true;
    } else {
      _phoneState = false;
    }
  }

  void _checkPwd() {
    if (_pwdcontroller.text.isNotEmpty &&
        _pwdcontroller.text.trim().length >= 6 &&
        _pwdcontroller.text.trim().length <= 10) {
      _pwdState = true;
    } else {
      _pwdState = false;
    }
  }

  @override
  void initState() {
    // TODO: implement initState

    super.initState();
  }

  login() async {
    FocusScope.of(context).requestFocus(FocusNode());
    Map<String, String> map = new Map();
    map["mobile"] = _phonecontroller.text.trim();
    map["password"] = _pwdcontroller.text.trim();
    SharedPreferences pref = await SharedPreferences.getInstance();
    String api = HttpHelper.API_UserLog;
    if (pref.getString('role') == "0") {
      //车商
      // api=HttpHelper.API_LoginBusiness;
      map["type"] = "2";
    } else {
      map["type"] = "1";
    }
    if (pref.getString('registeid') != null) {
      map["registed_Id"] = pref.getString('registeid');
    }

    HttpHelper.post(api, (data) async {
      if (data != null) {
        print(data);
        Toast.show(data["msg"], context);

        if (data["code"].toString() == "1") {
          pref.setString('islogin', '1');
          pref.setString('role', roles);
          pref.setString("uid", data["info"]["id"].toString());
          // pref.setStringList('userinfo', data["info"]);
          Navigator.of(context).pushAndRemoveUntil(
              new MaterialPageRoute(builder: (context) => new MyApp()),
              (route) => route == null);
          // Navigator.pushAndRemoveUntil(context, new MaterialPageRoute(builder: (context) => new MyApp()), (route) => route == null);
          //Navigator.popAndPushNamed(context, "index");
          // Navigator.popAndPushNamed(context, routeName)
          //pref.setStringList('userinfo', data["info"]);
          // Navigator.of(context).popUntil(ModalRoute.withName("index"));
          //Navigator.pop(context);
          // Navigator.pushNamed(context, "index");
          //runApp(MyApp());
          Navigator.pushReplacementNamed(context, "index");
        }
      }
    }, params: map);
  }

  @override
  Widget build(BuildContext context) {
    return
        // new MaterialApp(
        //   title: '登录',
        //   home:
        new Scaffold(
      appBar: new AppBar(
        title: new Text(
          '登录',
          style: TextStyle(color: Colors.black),
        ),
        backgroundColor: Colors.white,
        elevation: 0,
        iconTheme: IconThemeData(
          color: Colors.black, //修改颜色
        ),
        // backgroundColor: Color.fromRGBO(255, 204, 48, 1),
      ),
      body: new ListView(
        children: <Widget>[
          new Column(
            mainAxisSize: MainAxisSize.max,
            mainAxisAlignment: MainAxisAlignment.start,
            children: <Widget>[
              new Padding(
                  padding: new EdgeInsets.all(30.0),
                  child: new Image.asset(
                    'resource/images/user/user6.png',
                    scale: 1.2,
                  )),
              new Padding(
                  padding: new EdgeInsets.fromLTRB(20.0, 0.0, 20.0, 15.0),
                  child: new Container(
                      decoration: new BoxDecoration(
//背景
                        color: Colors.white,
                        //设置四周圆角 角度 这里的角度应该为 父Container height 的一半
                        borderRadius: BorderRadius.all(Radius.circular(5.0)),
                        //设置四周边框
                        border: new Border.all(
                            width: 1, color: Color.fromRGBO(225, 225, 225, 1)),
                      ),
                      child: new Column(children: <Widget>[
                        new Padding(
                            padding:
                                new EdgeInsets.fromLTRB(20.0, 0.0, 20.0, 0.0),
                            child: new Container(
                              height: 52,
                              child: new Stack(
                                alignment: new Alignment(1.0, 1.0),
                                //statck
                                children: <Widget>[
                                  new Row(
                                      mainAxisAlignment:
                                          MainAxisAlignment.spaceEvenly,
                                      children: [
                                        new Padding(
                                          padding: new EdgeInsets.fromLTRB(
                                              0.0, 0.0, 5.0, 0.0),
                                          child: new Image.asset(
                                            'resource/images/user/user7.png',
                                            width: 20.0,
                                            height: 20.0,
                                            fit: BoxFit.fill,
                                          ),
                                        ),
                                        new Expanded(
                                          child: new TextField(
                                            controller: _phonecontroller,
                                            keyboardType: TextInputType.number,
                                            decoration: new InputDecoration(
                                              border: InputBorder.none,
                                              hintText: '请输入用户名',
                                            ),
                                          ),
                                        ),
                                      ]),
                                  new IconButton(
                                    icon: new Icon(Icons.clear,
                                        color:
                                            Color.fromRGBO(235, 235, 235, 1)),
                                    onPressed: () {
                                      _phonecontroller.clear();
                                    },
                                  ),
                                ],
                              ),
                            )),
                        new Padding(
                          padding: new EdgeInsets.fromLTRB(0.0, 1.0, 0.0, 0.0),
                          child: Container(
                            height: 1,
                            color: Color.fromRGBO(225, 225, 225, 1),
                          ),
                        ),
                        new Padding(
                            padding:
                                new EdgeInsets.fromLTRB(20.0, 0.0, 20.0, 0.0),
                            child: new Container(
                              height: 52,
                              child: new Row(
                                  mainAxisAlignment:
                                      MainAxisAlignment.spaceEvenly,
                                  children: [
                                    new Padding(
                                      padding: new EdgeInsets.fromLTRB(
                                          0.0, 0.0, 5.0, 0.0),
                                      child: new Image.asset(
                                        'resource/images/user/user8.png',
                                        width: 20.0,
                                        height: 20.0,
                                        fit: BoxFit.fill,
                                      ),
                                    ),
                                    new Expanded(
                                      child: new TextField(
                                        controller: _pwdcontroller,
                                        decoration: new InputDecoration(
                                          border: InputBorder.none,
                                          hintText: '请输入密码',
                                          suffixIcon: new IconButton(
                                            icon: new Icon(Icons.clear,
                                                color: Color.fromRGBO(
                                                    235, 235, 235, 1)),
                                            onPressed: () {
                                              _pwdcontroller.clear();
                                            },
                                          ),
                                        ),
                                        obscureText: true,
                                      ),
                                    ),
                                  ]),
                            )),
                        // new Padding(
                        //   padding:
                        //       new EdgeInsets.fromLTRB(20.0, 1.0, 20.0, 40.0),
                        //   child: Container(
                        //     height: 1,
                        //     color: Color.fromRGBO(225, 225, 225, 1),
                        //   ),
                        // ),
                      ]))),
              Padding(
                  padding: new EdgeInsets.fromLTRB(20.0, 0.0, 20.0, 0.0),
                  child: new Container(
                    width: double.infinity,
                    child: new Card(
                      color: Color.fromRGBO(27, 182, 251, 1),
                      elevation: 16.0,
                      child: new FlatButton(
                        child: new Padding(
                          padding: new EdgeInsets.all(0.0),
                          child: new Text(
                            '登录',
                            style: new TextStyle(
                                color: Colors.white, fontSize: 16.0),
                          ),
                        ),
                        onPressed: () {
                          _checkPhone();
                          _checkPwd();
                          if (_phoneState && _pwdState) {
                            //_checkStr = '页面跳转下期见咯！';
                            login();
                          } else {
                            if (!_phoneState) {
                              _checkStr = '请输入11位手机号！';
                            } else if (!_pwdState) {
                              _checkStr = '请输入6-10位密码！';
                            }
                            Toast.show(_checkStr, context);
                          }
                        },
                      ),
                    ),
                  )),
              Container(
                height: 40,
                margin: new EdgeInsets.only(top: 15),
                child: GestureDetector(
                    behavior: HitTestBehavior.opaque,
                    onTap: () async {
                      SharedPreferences pref =
                          await SharedPreferences.getInstance();
                      pref.setString("role", widget.role);
                      Navigator.pushNamed(context, "forgetpass");
                      // print("传入的角色id："+widget.role);
                    },
                    child: Center(
                      child: Text("忘记密码"),
                    )),
              ),
              // Padding(
              //     padding: new EdgeInsets.fromLTRB(25, 10, 25, 10),
              //     child: Row(
              //       children: <Widget>[
              //         Expanded(
              //           child: new GestureDetector(
              //             child: Align(
              //               alignment: Alignment.centerLeft,
              //               child: Text('注册账号'),
              //             ),
              //             onTap: () {
              //               if(roles=="1"){
              //               Navigator.pushNamed(context, "regist");
              //               }else{
              //                 Navigator.pushNamed(context, "csapply");
              //               }
              //             },
              //           ),
              //           // child: new FlatButton(
              //           //     onPressed: () {
              //           //       Navigator.pushNamed(context, "regist");
              //           //     },
              //           //     child: Text('没账号？点击注册'))
              //         ),
              //         // Expanded(child: new Container(
              //         //   width: 0,
              //         //   color: Colors.red,
              //         //   height:40

              //         // )),
              //         Expanded(
              //           child: new GestureDetector(
              //             child: Align(
              //               alignment: Alignment.centerRight,
              //               child: Text('忘记密码'),
              //             ),
              //             onTap: () {

              //               Navigator.pushNamed(context, "forgetpass");
              //             },
              //           ),
              //           // child: new FlatButton(
              //           //     onPressed: () {
              //           //       Navigator.pushNamed(context, "forgetpass");
              //           //     },
              //           //     child: Text(
              //           //       '忘记密码',
              //           //       textAlign: TextAlign.right,
              //           //     )),
              //         )
              //       ],
              //     ))
              // roles == "1"
              //     ? Padding(
              //         padding: new EdgeInsets.fromLTRB(15, 0, 15, 0),
              //         child: Center(
              //           child: new FlatButton(
              //             child: Text('没账号？点击注册'),
              //             onPressed: () {
              //               Navigator.pushNamed(context, "regist");
              //             },
              //           ),
              //         ),
              //       )
              //     : Text(''),
              // roles == "1"
              //     ? Padding(
              //         padding: new EdgeInsets.fromLTRB(15, 0, 15, 0),
              //         child: Center(
              //           child: new FlatButton(
              //             child: Text('忘记密码'),
              //             onPressed: () {
              //               Navigator.pushNamed(context, "forgetpass");
              //             },
              //           ),
              //         ),
              //       )
              //     : Text('')
            ],
          ),
        ],
      ),
    );
  }
}
